import React, { Fragment, useEffect } from 'react';
import { history } from 'umi';
import { connect } from 'umi';
import moment from 'moment';
import { Form, Button, Table, Row, Col } from 'antd';
import { QuickForm, utils } from 'vv-frontend-components';
import Locale from '@/utils/locale';
import DateRange from '@/components/DateRange';
import { formatSecond } from '@/utils/utils';
import Pagination from '@/components/Pagination';
import OrganizationSelect from '@/components/OrganizationSelect';
import styles from './Rank.less';

const { locale } = new Locale('stat.overtime');
const { deepTrim } = utils;

const List = ({ tabType, form, rank, loading, dispatch, location }) => {
    const { getFieldsValue } = form;
    const { extra } = rank;
    const { pagination, list: data } = rank[tabType];
    const { query } = location;
    const { companyCode, departmentCode, startTime, endTime, dateType, quarter } = query;

    // const user = localStorage.getItem('user')
    //     ? JSON.parse(localStorage.getItem('user'))
    //     : {};

    const config = [
        {
            field: 'companyCode',
            label: '行政机构',
            config: {
                initialValue: companyCode || undefined
            },
            component: <OrganizationSelect />
        },
        {
            field: 'departmentCode',
            label: '组织机构',
            config: {
                initialValue: departmentCode || undefined
            },
            component: <OrganizationSelect isFunctional isNeedPermission />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        !startTime ? moment().startOf('year') : moment(startTime),
                        !endTime ? moment().endOf('year') : moment(endTime)
                    ],
                    type: !dateType ? 'year' : dateType,
                    quarter: quarter ? Number(quarter) : 1
                }
            },
            component: <DateRange allowClear={false} />
        },
        {
            component: (
                <div>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                </div>
            )
        }
    ];

    const indexNumRander = index => {
        // const colorMap = {
        //     0: 'red',
        //     1: 'orange',
        //     2: 'yellow',
        //     3: 'green',
        //     4: 'blue'
        // };
        const num = (pagination.current - 1) * pagination.pageSize + index + 1;
        return <span className={`${styles.number} ${num < 6 && styles.orange}`}>{num}</span>;
    };

    const handleRender = (text, record) => {
        const fieldsValue = getFieldsValue();
        return (
            <span className="actionTd">
                <a
                    href="#"
                    onClick={e => {
                        e.preventDefault();
                        history.push({
                            pathname: '/office/institutions/flowManage/fullApprovalProcess',
                            query: {
                                title: record.name || record.employeeName,
                                companyCode: fieldsValue.companyCode || '',
                                departmentCode: fieldsValue.departmentCode || ''
                            }
                        });
                    }}
                >
                    流程详情
                </a>
            </span>
        );
    };

    const columnsMap = {
        approver: [
            // {
            //     title: '工号',
            //     dataIndex: 'employeeId',
            //     key: 'employeeId'
            // },
            {
                title: '',
                render: (text, record, index) => indexNumRander(index)
            },
            {
                title: '姓名',
                dataIndex: 'employeeName',
                key: 'employeeName'
            },
            {
                title: '职位',
                dataIndex: 'post',
                key: 'post'
            },
            {
                title: '审批次数',
                dataIndex: 'number',
                key: 'number',
                sorter: true,
                sortDirections: ['descend']
            },
            {
                title: '平均审批时间',
                dataIndex: 'avgTime',
                key: 'avgTime',
                sorter: true,
                render: text => formatSecond(Number(text / 1000 / 60), true, true)
            }
        ],
        commonWorkflow: [
            {
                title: '',
                align: 'center',
                render: (text, record, index) => indexNumRander(index)
            },
            {
                title: '流程名称',
                dataIndex: 'name',
                key: 'name'
            },
            {
                title: '流程分组',
                dataIndex: 'categoryName',
                key: 'categoryName'
            },
            {
                title: '申请次数',
                dataIndex: 'count',
                key: 'count'
            },
            {
                title: '申请人数',
                dataIndex: 'humanCount',
                key: 'humanCount'
            },
            {
                title: '操作',
                width: '10%',
                render: handleRender
            }
        ],
        applicant: [
            {
                title: '',
                render: (text, record, index) => indexNumRander(index)
            },
            {
                title: '姓名',
                dataIndex: 'employeeName',
                key: 'employeeName'
            },
            {
                title: '部门',
                dataIndex: 'departmentName',
                key: 'departmentName'
            },
            {
                title: '职位',
                dataIndex: 'postName',
                key: 'postName'
            },
            {
                title: '总申请',
                dataIndex: 'totalApplyCount',
                key: 'totalApplyCount'
            },
            // {
            //     title: '考勤类',
            //     dataIndex: 'attendanceApplyCount',
            //     key: 'attendanceApplyCount'
            // },
            // {
            //     title: '财务类',
            //     dataIndex: 'financialApplyCount',
            //     key: 'financialApplyCount'
            // },
            // {
            //     title: '人事类',
            //     dataIndex: 'personnelMattersApplyCount',
            //     key: 'personnelMattersApply'
            // },
            {
                title: '操作',
                width: '10%',
                render: handleRender
            }
        ]
    };

    const columns = columnsMap[tabType];

    const fetchList = () => {
        const fieldsValue = getFieldsValue();
        const { date = { range: [] } } = fieldsValue;
        const queryExtra = {};
        if (tabType === 'approver') {
            queryExtra.processStatus = extra.processStatus || 4;
        }
        dispatch(
            deepTrim({
                type: 'rank/fetchList',
                fetchType: tabType,
                payload: {
                    companyCode: fieldsValue.companyCode || '',
                    departmentCode: fieldsValue.departmentCode || '',
                    pageNo: pagination.current,
                    pageSize: pagination.pageSize,
                    startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD 00:00:00') : '',
                    endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD 23:59:59') : '',
                    ...queryExtra
                }
            })
        );
    };

    const handleSubmit = async e => {
        e.preventDefault();
        if (pagination.current !== 1) {
            await dispatch({
                type: 'rank/save',
                fetchType: tabType,
                payload: {
                    [tabType]: {
                        pagination: {
                            ...pagination,
                            current: 1
                        }
                    }
                }
            });
        } else {
            fetchList();
        }
    };

    const changeCurrent = async (tabPagination, filters, sorter) => {
        const updateExtra = {};
        if (tabType === 'approver' && sorter) {
            if (sorter.field === 'avgTime') {
                updateExtra.processStatus = sorter.order === 'ascend' ? 6 : 5;
            }
            if (sorter.field === 'number') {
                updateExtra.processStatus = 4;
            }
        }
        await dispatch({
            type: 'rank/save',
            payload: {
                extra: { ...updateExtra },
                [tabType]: {
                    pagination: {
                        ...pagination,
                        ...tabPagination
                    }
                }
            }
        });
    };

    useEffect(
        () =>
            // 下次展示时，重置页码
            () => {
                dispatch({
                    type: 'rank/save',
                    fetchType: tabType,
                    payload: {
                        [tabType]: {
                            pagination: {
                                ...pagination,
                                current: 1
                            }
                        }
                    }
                });
            },
        []
    );

    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [tabType, pagination.pageSize, pagination.current, extra]);

    return (
        <Fragment>
            <Form layout="inline" style={{ marginBottom: 15 }} onSubmit={handleSubmit}>
                <QuickForm form={form} config={config} />
            </Form>
            <Table
                bordered
                columns={columns}
                loading={loading.models.rank}
                dataSource={data}
                rowKey="id"
                onChange={changeCurrent}
                pagination={false}
            />
            <Row>
                <Col>
                    <Pagination {...pagination} onChange={changeCurrent} />
                </Col>
            </Row>
        </Fragment>
    );
};

export default connect(({ rank, loading }) => ({
    rank,
    loading
}))(Form.create()(List));
